package com.example.umbrella.util;

public class DataConverter {
    public static String bytesToAscii(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return "Empty";
        }
        
        // 直接将字节数组转换为字符串
        return new String(bytes);
    }

    public static String bytesToHex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return "Empty";
        }
        
        StringBuilder hex = new StringBuilder();
        for (byte b : bytes) {
            hex.append(String.format("%02X ", b));
        }
        return hex.toString().trim();
    }

    public static String hexToAscii(String hexStr) {
        if (hexStr == null || hexStr.isEmpty() || hexStr.equals("Empty")) {
            return "Empty";
        }

        try {
            // 移除空格
            hexStr = hexStr.replaceAll("\\s", "");
            
            StringBuilder output = new StringBuilder();
            for (int i = 0; i < hexStr.length(); i += 2) {
                String str = hexStr.substring(i, i + 2);
                output.append((char) Integer.parseInt(str, 16));
            }
            return output.toString();
        } catch (Exception e) {
            return "Invalid data";
        }
    }
} 